// packageF/tourAround/tourCityList/tourCityList.js
const app = getApp();
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    cityCode: "",
    city: "",
    cityName: "",
    keyword: "",
    search: "", // 搜索关键字
    searchFlag: false,
    cities: [], // 城市配置信息
    cityData: [], // 储存城市配置信息
    cityArr: [], //处理好数据结构
    historyList: [], //搜索站点的历史记录
    hostCities: [], // 热门城市
    timer: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if ((options.cityCode ?? "") !== "") {
      this.setData({
        cityCode: options.cityCode,
        city: options.city,
        cityName: decodeURIComponent(options.city)
      })
    }
    try {
      let History = wx.getStorageSync("historyList") || [];
      if (History.length > 0) {
        this.setData({
          hostCities: JSON.parse(History)
        })
      }
    } catch (error) {
      console.log(error);
    }
    this.setData({
      searchFlag: false
    })
    this.aroundLocation();

  },
  // 搜索
  searchCity(event) {
    console.log(event);
    let value = event.detail.value;
    this.setData({
      search: value
    })
    if (this.data.search !== "") {
      this.setData({
        city: this.data.search,
        keyword:this.data.search,
        cityCode: ''
      })
      if (this.data.timer) clearTimeout(this.data.timer); //防抖
      this.data.timer = setTimeout(() => {
        this.setData({
          searchFlag: true
        })
        // this.stopMove();
        this.aroundLocation();
      }, 100);

    } else {
      this.setData({
        searchFlag: false
      })
      // this.Move();
    }
  },
  formattingData(arr, group_key) {
    let map = {};
    let res = [];

    for (let i = 0; i < arr.length; i++) {
      let ai = arr[i];
      if (!map[ai[group_key]]) {
        map[ai[group_key]] = [ai];
      } else {
        map[ai[group_key]].push(ai);
      }
    }
    Object.keys(map).forEach((key, index) => {
      res.push({
        index: index,
        [group_key]: key,
        list: map[key]
      });
    });
    return res;
  },
  filterViewMove() {
    return this.data.searchFlag;
  },
  aroundLocation() {
      let urlStr = app.getNetAddresss("plugin.travel-around.frontend.index.index.getTravelAroundLocation");
      let json = {
        cityCode: this.data.cityCode,
        city: this.data.city,
        keyword: this.data.keyword
      };
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data
          if (res.result == 1) {
            if (!res.data.matching) {
              this.setData({
                searchFlag: false
              })
              // this.Move();
            }
            let cityCode = wx.getStorageSync('cityCode') || "";
            let cityArr = [];
            if (cityCode) {
              cityArr = JSON.parse(wx.getStorageSync('cityCodeArr')) || [];
            } else {
              cityArr = this.formattingData(res.data.all, "firstWord");
              wx.setStorageSync("cityCodeArr", JSON.stringify(cityArr));
              wx.setStorageSync("cityCode", 'firstWord');
            }
            this.setData({
              cityData: res.data.all,
              matching: res.data.matching || [],
              cityArr: cityArr
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
  },
  searchSites(event) {
    let {city,citycode} = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/packageF/tourAround/travelIndex/travelIndex?city=${city}&cityCode=${citycode}&localCity=${city}`,
    });
    this.historyCity(city, citycode);
  },
  historyCity(city, cityCode) {
    let arr = wx.getStorageSync('historyList') || [];
    let searchArr = [];
    if (arr.length > 0) {
      arr = JSON.parse(arr);
      let len = arr.length;
      if (len >= 10) {
        arr.pop();
      }
    }
    arr.unshift({ name: city, cityCode: cityCode });
    searchArr = arr.filter((currentValue, currentIndex, selfArr) => {
      //去重
      return selfArr.findIndex(x => x.name === currentValue.name) === currentIndex;
    });
    wx.setStorageSync("historyList", JSON.stringify(searchArr));
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('页面隐藏页面隐藏');
    wx.setStorageSync("cityCodeArr", JSON.stringify([]));
    wx.setStorageSync("cityCode", '');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('监听页面卸载');
    wx.setStorageSync("cityCodeArr", JSON.stringify([]));
    wx.setStorageSync("cityCode", '');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})